package m.jclecai.com.activity;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.ProofBean;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.ChannelUtil;
import m.jclecai.com.utils.MyToast;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.utils.http.responseBody.BaseBody;

import static m.jclecai.com.activity.RegisterActivity.IS_WEI_XIN;

/**
 * Created by ZD on 2017/5/22.
 */

public class BindPhoneActivity extends BaseActivity {

    UserBean userBean;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.ll_bind)
    LinearLayout llBind;
    @BindView(R.id.et_init_phone)
    EditText etInitPhone;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.tv_send_proof)
    TextView tvSendProof;
    @BindView(R.id.tv_update)
    TextView tvUpdate;
    @BindView(R.id.ll_update)
    LinearLayout llUpdate;
    @BindView(R.id.et_first_bind_init_phone)
    EditText etFirstBindInitPhone;
    @BindView(R.id.et_first_bind_code)
    EditText etFirstBindCode;
    @BindView(R.id.tv_first_bind_send_proof)
    TextView tvFirstBindSendProof;
    @BindView(R.id.tv_first_bind_update)
    TextView tvFirstBindUpdate;
    @BindView(R.id.ll_first_bind)
    LinearLayout llFirstBind;

    @Override
    public int getContentView() {
        return R.layout.activity_bind_phone;
    }

    @Override
    public void initView() {
        super.initView();
        setTitle("绑定手机号码");
        leftOptionText("");
    }



    @Override
    public void initData() {
        super.initData();
        userBean = PreferenceUtil.readUser(this);
        llBind.setVisibility(View.GONE);
        llUpdate.setVisibility(View.GONE);
        llFirstBind.setVisibility(View.GONE);
        if (userBean != null) {
            if(TextUtils.isEmpty(userBean.getPhone())){
                llFirstBind.setVisibility(View.VISIBLE);
            }else {
                llBind.setVisibility(View.VISIBLE);
                tvPhone.setText(BaseUtils.formatPhone(userBean.getPhone()));
            }
        } else {
            llFirstBind.setVisibility(View.VISIBLE);
        }
    }


    //绑定或更换手机号
    private void bindPhone() {
        //需要绑定的手机号
        String phone = etFirstBindInitPhone.getText().toString().trim();
        String code = etFirstBindCode.getText().toString();
        if(llUpdate.getVisibility() == View.VISIBLE){
            phone = etPhone.getText().toString();
            code = etCode.getText().toString();
        }
        if (TextUtils.isEmpty(phone) || !BaseUtils.isMobileNO(phone)) {
            MyToast.showToast(this, "请输入正确的手机号码");
            return;
        }
        if (TextUtils.isEmpty(code)) {
            MyToast.showToast(this, "请输入手机验证码");
            return;
        }
        showDialog();
        final HashMap<String, String> pair = new HashMap<>();
        //第一次绑定的时候vphone是验证码
        pair.put("vphone", code);//短信验证码
        pair.put("user", PreferenceUtil.getUserName(this));//用户名
        pair.put("phone", phone);//绑定的手机号
        pair.put("password", PreferenceUtil.getPassword(this));//密码
        pair.put("flag", "4");//标志flag=2 (修改密码)flag=3 (绑定手机)flag=4 (修改并绑定手机)
        pair.put("appstore", ChannelUtil.getChannel());//标志flag=2 (修改密码)flag=3 (绑定手机)flag=4 (修改并绑定手机)
        //
        HttpManager.postAsyn(Constant_Url.CHECK_PHONE_RANDNUM_URL, new HttpManager.StringCallback() {

            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay(getString(R.string.error_network));
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                if (!TextUtils.isEmpty(response)) {
                    BaseBody baseBody = FastOk.get(response, BaseBody.class);
                    if(baseBody != null){
                        MyToast.showToast(BindPhoneActivity.this,baseBody.getMessage());
                        if(baseBody.getStatus() == 0){
                            userBean.setPhone(pair.get("phone"));
                            PreferenceUtil.writeUser(BindPhoneActivity.this,userBean);
                            finish();
                        }
                    }else {
                        DisPlay(getString(R.string.error_network));
                    }
                }
            }
        }, pair);

    }


    //未绑定手机号时发送验证码
    private void sendProofWithOutBind() {

        //这里是绑定手机号发送验证码的逻辑
        if (PreferenceUtil.readBoolean(this,PreferenceUtil.WEI_XIN_IS_BIND_PHONE_NUMBER,true)) {
            sendNormalProofCode();
        }else{
            //这里表示的是微信登陆的但是没有绑定手机号；
            sendWeiXinProofCode();
        }
    }

    public void sendNormalProofCode(){

        String phone = etFirstBindInitPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone) || !BaseUtils.isMobileNO(phone)) {
            MyToast.showToast(this, "请输入正确的手机号码");
            return;
        }
        showDialog();
        HashMap<String, String> pair = new HashMap<>();
        pair.put("phone", phone);
        HttpManager.postAsyn(Constant_Url.PROOF_URL, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                MyToast.showToast(BindPhoneActivity.this, "验证码发送失败");
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                ProofBean proofBean = FastOk.get(response, ProofBean.class);
                if (proofBean != null) {
                    MyToast.showToast(BindPhoneActivity.this, proofBean.getMessage());
                    if("0".equals(proofBean.getStatus()))
                        BaseUtils.countDowm(BindPhoneActivity.this, 60, tvFirstBindSendProof);
                }else {
                    MyToast.showToast(BindPhoneActivity.this, "验证码发送失败");
                }
            }
        }, pair);
    }



    /**
     * 这里是发送微信绑定手机号的时候发送验证码
     */
    private void sendWeiXinProofCode() {

        String phone = etFirstBindInitPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone) || !BaseUtils.isMobileNO(phone)) {
            MyToast.showToast(BindPhoneActivity.this, "请输入正确的手机号码");
            return;
        }

        BaseUtils.countDowm(BindPhoneActivity.this, 60,tvFirstBindSendProof);
        HashMap<String, String> pair = new HashMap<>();
        pair.put("phone", phone);
        pair.put("user", PreferenceUtil.getUserName(this));
        pair.put("sessionid", "android");
        pair.put("password", PreferenceUtil.getPassword(this));
        HttpManager.postAsyn(Constant_Url.WEI_BIND_PHONE_NUMBER, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                MyToast.showToast(BindPhoneActivity.this, "验证码发送失败");
            }

            @Override
            public void onResponse(String response) {
                ProofBean proofBean = FastOk.get(response, ProofBean.class);
                if (proofBean != null)
                    //MyToast.showToast(RegisterActivity.this, proofBean.getMessage());
                    DisPlay(proofBean.getMessage());
                else
                    DisPlay("网络异常！！！");
                //MyToast.showToast(RegisterActivity.this, getString(R.string.error_network));

            }
        }, pair);

    }

    //更改手机号时发送验证码
    private void sendProofChangeBind() {
        //新手机
        String phone = etPhone.getText().toString();
        //原手机
        String vphone= etInitPhone.getText().toString();
        if (TextUtils.isEmpty(vphone) || !BaseUtils.isMobileNO(vphone)) {
            MyToast.showToast(this, "请输入旧的手机号码");
            return;
        }
        if (TextUtils.isEmpty(phone) || !BaseUtils.isMobileNO(phone)) {
            MyToast.showToast(this, "请输入新的手机号码");
            return;
        }
        showDialog();
        Map<String, String> pair = new HashMap<>();
        pair.put("user", PreferenceUtil.getUserName(this));
        pair.put("password", PreferenceUtil.getPassword(this));
        //新手机
        pair.put("phone", phone);
        //原手机
        pair.put("vphone", vphone);
        pair.put("sessionid", "et_code");
        HttpManager.postAsyn(Constant_Url.BIND_PHONE_CODE, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                MyToast.showToast(BindPhoneActivity.this, "验证码发送失败");
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                BaseBody baseBody = FastOk.get(response, BaseBody.class);
                if (baseBody != null) {
                    MyToast.showToast(BindPhoneActivity.this, baseBody.getMessage());
                    if(baseBody.getStatus() == 0){
                        BaseUtils.countDowm(BindPhoneActivity.this, 60, tvSendProof);
                    }
                } else {
                    MyToast.showToast(BindPhoneActivity.this, "验证码发送失败");
                }
            }
        }, pair);
    }

    @OnClick({R.id.tv_next, R.id.tv_first_bind_update, R.id.tv_update})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_next:
                llBind.setVisibility(View.GONE);
                //未绑定
                if("0".equals(userBean.getPhonenumberid())){
                    llFirstBind.setVisibility(View.VISIBLE);
                }else {//更改绑定
                    llUpdate.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.tv_first_bind_update:
            case R.id.tv_update:
                bindPhone();
                break;
        }
    }

    @OnClick({R.id.tv_first_bind_send_proof,R.id.tv_send_proof})
    public void onProofClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_first_bind_send_proof:
                sendProofWithOutBind();
                break;
            case R.id.tv_send_proof:
                sendProofChangeBind();
                break;
        }
    }

    private static final String IS_WEI_XIN_SEND_CODE="is_wei_xin";


    public static Intent getInstanceIntent(Context context,boolean isWeixinSendCode){

        Intent intent = new Intent(context, BindPhoneActivity.class);
        intent.putExtra(IS_WEI_XIN,isWeixinSendCode);
        return intent;
    }
}
